package com.eds.controller;

import com.eds.dto.BackOrderDTO;
import com.eds.dto.BackOrdersBoardDTO;
import com.eds.dto.DashboardTrendsDTO;
import com.eds.dto.PageUtils;
import com.eds.feign.CourseFeign;
import com.eds.feign.PayFeign;
import com.eds.pojo.BaseResult;
import com.eds.pojo.CodeEnum;
import com.eds.service.OrdersService;
import com.pojo.Course;
import com.pojo.Orders;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;


/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName：OrderController
 * @Author: vvSmile
 * @Date: 2025/04/01
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@RestController
@RequestMapping("/ordersController")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private CourseFeign courseFeign;
    @Autowired
    private PayFeign payFeign;


    //1.创建订单
    @PostMapping("/createOrders")
    public Boolean createOrders(@RequestBody Orders orders) {
        Boolean createOrderReturn = ordersService.createOrders(orders);
        return createOrderReturn;
    }


    //2.根据OrdersId查询订单
    @GetMapping("/selectOrdersByOrdersId")
    BaseResult selectOrdersByOrdersId(@RequestParam("ordersId") String ordersId) {
        Orders orders = ordersService.selectOrdersByOrdersId(ordersId);
        if (orders == null) {
            return BaseResult.error(CodeEnum.ORDERS_SELECT_ERROR);
        }
        return BaseResult.ok("查询成功！", orders);
    }

    //3.取消订单
    @GetMapping("/cancelOrders")
    BaseResult cancelOrders(@RequestParam("ordersId") String ordersId) {
        Boolean aBoolean = ordersService.cancelOrders(ordersId);
        if (!aBoolean) {
            return BaseResult.error(CodeEnum.ORDERS_DELETE_ERROR);
        }
        return BaseResult.ok("取消订单成功！", aBoolean);
    }

    //4.支付
    @PostMapping("/payOrders")
    public BaseResult payOrders(@RequestHeader("authorization") String token, @RequestBody Orders orders) {
        if (orders.getPaymentChannel().equals("wechat")) {
            ordersService.cancelOrders(orders.getOrdersId());
            return BaseResult.ok("该功能未开发，请选择其他方式！");
        } else if (orders.getPaymentChannel().equals("bankcard")) {
            ordersService.cancelOrders(orders.getOrdersId());
            return BaseResult.ok("该功能未开发，请选择其他方式！");
        }
        //查询课程信息
        Course course = courseFeign.ordersSelectCourseByScheduleId(token, orders.getScheduleId());
        if (course.getPrice().compareTo(BigDecimal.ZERO) == 0) {
            Orders updateFreeOrders = ordersService.updateOrdersPayFreeStatus(orders.getOrdersId(), orders.getPaymentAmount(), orders.getPaymentChannel(), orders.getTransactionId());
            if (updateFreeOrders != null) {
                //更新课程预约状态
                courseFeign.updateBookingStatus(orders.getScheduleId(), 1);
                return BaseResult.ok("免费课程，无需支付！", updateFreeOrders);
            } else
                return BaseResult.error(CodeEnum.ORDERS_PAY_ERROR);
        } else {
            //调用支付宝接口
            Map aNative = payFeign.createNative(orders.getOrdersId(), orders.getPaymentAmount().multiply(new java.math.BigDecimal(100)).longValue() + "");
            if (aNative == null) {
                return BaseResult.error(CodeEnum.ORDERS_PAY_ERROR);
            }
            //更新课程预约状态
            courseFeign.updateBookingStatus(orders.getScheduleId(), 1);
            return BaseResult.ok("创建订单成功！", aNative);
        }


    }


    //5.查询支付状态
    @GetMapping("/queryPayStatus")
    public BaseResult queryPayStatus(@RequestParam("ordersId") String ordersId) throws JSONException {
        //支付宝支付成功后调用
        String paymentChannel = "alipay";
        //调用支付宝查询支付状态
        BaseResult baseResult = payFeign.queryPayStatus(ordersId);
        //处理支付宝返回的数据
        Object data = baseResult.getData();
        //判断是否是map
        if (data instanceof Map) {
            Map<String, Object> payReturn = (Map<String, Object>) data;
            String tradeNo = (String) payReturn.get("trade_no");
            String alipayData = (String) payReturn.get("response");
            //将支付宝返回的数据转换为json对象
            JSONObject jsonObject = new JSONObject(alipayData);
            JSONObject alipayTradeQueryResponse = jsonObject.getJSONObject("alipay_trade_query_response");
            String buyerLogonId = alipayTradeQueryResponse.getString("buyer_logon_id");
            String buyerPayAmount = alipayTradeQueryResponse.getString("buyer_pay_amount");
            //更新订单状态
            ordersService.updateOrdersPayStatus(ordersId, paymentChannel, tradeNo, buyerLogonId, buyerPayAmount);
        }
        return baseResult;
    }


    //6.根据课程时间和用户id和课程id查询订单（课程评论使用）
    @GetMapping("/selectOrdersByScheduleUserCourseId")
    Orders selectOrdersByScheduleUserCourseId(Long scheduleId, Long userId, Long courseId) {
        return ordersService.selectOrdersByScheduleUserCourseId(scheduleId, userId, courseId);
    }

    //7.支付成功后退款预约
    @GetMapping("/refund")
    public BaseResult refund(@RequestHeader("authorization") String token, @RequestParam("scheduleId") String scheduleId) {
        //调用退款接口
        BaseResult result = ordersService.refundAndCancelBooking(token, scheduleId);
        if (result.getCode() == 200) {
            return BaseResult.ok("退款成功！", result);
        }
        return BaseResult.error(CodeEnum.ORDERS_REFUND_ERROR);
    }

    //8.发送通知
    @GetMapping("/sendOrdersPaySuccessMessage")
    public BaseResult sendOrdersPaySuccessMessage(@RequestHeader("authorization") String token, @RequestParam("ordersId") String ordersId) {
        //发送数据到RabbitMQ更新通知消息
        ordersService.sendOrdersPaySuccessMessage(token, ordersId);
        return BaseResult.ok("发送成功！");
    }

    //9.查询所有订单
    @GetMapping("/selectAllOrders")
    public PageUtils selectAllOrders(@RequestParam("currentPage") int currentPage, @RequestParam("pageSize") int pageSize) {
        PageUtils<BackOrderDTO> ordersPage = ordersService.selectAllOrders(currentPage, pageSize);
        return ordersPage;
    }

    @GetMapping("/getOrdersBoard")
    public BaseResult getOrdersBoard() {
        BackOrdersBoardDTO ordersBoard = ordersService.getOrdersBoard();
        if (ordersBoard == null) {
            return BaseResult.error(CodeEnum.GET_ORDERS_BOARD_ERROR);
        }
        return BaseResult.ok("获取用户面板成功！", ordersBoard);
    }

    //获取面板趋势数据
    @GetMapping("/getTrendBoard")
    public BaseResult getTrendBoard() {
        DashboardTrendsDTO ordersTrend = ordersService.getDashboardTrends();
        if (ordersTrend == null) {
            return BaseResult.error(CodeEnum.GET_TREND_ERROR);
        }
        return BaseResult.ok("获取面板趋势成功！", ordersTrend);
    }
}



